package org.jradweb.tools.generator.maven;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

public abstract class BaseMojo extends AbstractMojo {
	/**
	 * @parameter expression="${project.build.directory}"
	 */	
	protected File buildPath;
	
	/**
	 * @parameter expression="${basedir}"
	 */	
	protected File baseDir;
	
	/**
	 *  @parameter expression="${project}"
	 */
	protected MavenProject project;
	
	/**
	 * @parameter expression="${project.groupId}"
	 */
	protected String groupId;
	
	/**
	 * @parameter expression="${project.artifactId}"
	 */
	protected String artifactId;

	
	public void execute() throws MojoExecutionException, MojoFailureException {
		this.getLog().info("project: "+project.getArtifactId());
		this.getLog().info("basedir: "+this.baseDir.getAbsolutePath());
		
		Thread currentThread = Thread.currentThread();
        ClassLoader oldClassLoader = currentThread.getContextClassLoader();

        try
        {
            currentThread.setContextClassLoader( getClassLoader() );
           
            doExecute();
        }
        finally
        {
            currentThread.setContextClassLoader( oldClassLoader );
        }
	}
	protected abstract void doExecute() throws  MojoExecutionException, MojoFailureException;

	public MavenProject getProject() {
		return project;
	}

	public File getBasedir() {
		return baseDir;
	}

	public void setProject(MavenProject project) {
		this.project = project;
	}

	public void setBasedir(File basedir) {
		this.baseDir = basedir;
	}
	
	private ClassLoader getClassLoader()
    {
        try
        {
            List classpathElements = project.getCompileClasspathElements();
            classpathElements.add( project.getBuild().getOutputDirectory() );
            classpathElements.add( project.getBuild().getTestOutputDirectory() );
            URL urls[] = new URL[classpathElements.size()];
            for ( int i = 0; i < classpathElements.size(); ++i )
            {
                urls[i] = new File( (String) classpathElements.get( i ) ).toURL();
            }
            return new URLClassLoader( urls, this.getClass().getClassLoader() );
        }
        catch ( Exception e )
        {
            getLog().debug( "Couldn't get the classloader." );
            return this.getClass().getClassLoader();
        }
    }

}
